// src/context/WebSocketContext.ts

import React, { createContext, useState, useEffect, Dispatch, SetStateAction } from 'react';

interface WebSocketContextType {
  messages: string[];
  send: (data: any) => void;
}

const WebSocketContext = createContext<WebSocketContextType | undefined>(undefined);

const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [messages, setMessages] = useState<string[]>([]);
  const [socket, setSocket] = useState<WebSocket | null>(null);

  useEffect(() => {
    const url = 'wss://your-websocket-url.com/socket'; // 替换为你的WebSocket URL
    const newSocket = new WebSocket(url);

    newSocket.onopen = () => {
      console.log('WebSocket connection opened');
    };

    newSocket.onmessage = (event: MessageEvent<string>) => {
      console.log('Received data:', event.data);
      setMessages((prevMessages) => [...prevMessages, event.data]);
    };

    newSocket.onclose = () => {
      console.log('WebSocket connection closed');
    };

    newSocket.onerror = (error: Event) => {
      console.error('WebSocket error:', error);
    };

    setSocket(newSocket);

    return () => {
      newSocket.close();
    };
  }, [url]);

  const send = (data: any) => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify(data));
    }
  };

  return (
    <WebSocketContext.Provider value={{ messages, send }}>
      {children}
    </WebSocketContext.Provider>
  );
};

export { WebSocketContext, WebSocketProvider };